<template>
  <div class="root">
    <el-container>
      <el-container>
        <el-aside class="aside" width="200px">
          <div class="aside_bg">
            <el-col :span="12">
              <h5 class="mb-2" style="padding-left: 20px; width: 100%;">Music Dream</h5>
              <el-menu default-active="1" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
                <el-menu-item index="4">
                  <span>Dashboard</span>
                </el-menu-item>
                <el-menu-item index="2">
                  <span>Manager</span>
                </el-menu-item>
              </el-menu>
            </el-col>
          </div>
        </el-aside>
        <el-container>
      <el-header class="header">
        <div class="button-group">
          <el-button type="primary" @click="upload" plain>Upload</el-button>
          <el-button type="primary" @click="pause" plain>Pause</el-button>
        </div>
      </el-header>
          <el-main class="main">
            <div class="main-container">
              <el-table class="table" :data="songs" stripe style="width: 100%; margin-top: 20px" row-style="height: 18px">
                <el-table-column prop="title" label="Title" width="220" show-overflow-tooltip />
                <el-table-column prop="artist" label="Artist" width="120" show-overflow-tooltip />
                <el-table-column prop="lyricist" label="Lyricist" width="120" show-overflow-tooltip />
                <el-table-column prop="composer" label="Composer" width="120" show-overflow-tooltip />
                <el-table-column prop="album" label="Album" show-overflow-tooltip />
                <el-table-column prop="genre" label="Genre" show-overflow-tooltip />
                <el-table-column prop="lyrics" label="Lyrics" show-overflow-tooltip />
                <el-table-column prop="release_date" label="Release Date" show-overflow-tooltip />
                <el-table-column prop="created_at" label="Created at" show-overflow-tooltip />
                <el-table-column prop="updated_at" label="Update at" show-overflow-tooltip />
                <el-table-column width="310" label="Operations">
                  <template #default="scope">
                    <el-button size="" :icon="VideoPlay" @click="play(scope.$index, scope.row)"></el-button>
                    <el-button size="" :icon="Edit" @click="handleEdit(scope.$index, scope.row)"></el-button>
                    <el-button size="" :icon="Delete" type="danger"
                      @click="handleDelete(scope.$index, scope.row)"></el-button>
                    <el-button size="" :icon="Download" type="primary"
                      @click="handleDownload(scope.$index, scope.row)"></el-button>
                  </template>
                </el-table-column>
              </el-table>

              <div class="pagination-block">
                <el-pagination v-model:current-page="current_page" v-model:page-size="page_size"
                  :page-sizes="[10, 20, 25, 30]" size="default" :disabled="disabled" :background="background"
                  layout="sizes, prev, pager, next" :total="total_count" @size-change="handleSizeChange"
                  @current-change="handleCurrentChange" />
              </div>
            <audio ref="audio_player" controls hidden="true" :src="current_song_url"></audio>
          </div>
          </el-main>
          <el-footer class="footer" height="50px">
            <div class="footer_bg"></div>
          </el-footer>
        </el-container>
      </el-container>
    </el-container>
    <Upload v-model="uploadDialogVisible"></Upload>
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, onMounted, nextTick } from "vue";
import { useRoute } from "vue-router";
import Upload from "./Upload.vue";
import {
  VideoPlay,
  Delete,
  Edit,
  Download,
} from '@element-plus/icons-vue'

import buildInfo from '../build-info.json';

import { ElContainer, ElHeader, ElAside, ElMain, ElFooter } from 'element-plus'

console.log('buildInfo:', buildInfo);

// const router = useRouter();
const route = useRoute();
const page_num = ref(1);
const page_size = ref(20);
const total_count = ref(0);
const songs = ref([]);
// const size = ref("default");
const disabled = ref(false);
const background = ref(true);


const current_page = ref(1)
const uploadDialogVisible = ref(false);

const current_song_url = ref('');
const audio_player = ref<HTMLAudioElement>();

async function play(_row: number, data: any) {
  try {
    let res = await axios.get(`/api/songs/get_download_url2/${data.song_id}`)
    current_song_url.value = res.data.data.url
    await nextTick();
    await audio_player.value?.play();
  }
  catch (err) {
    console.log('err:', err);
  }
}

async function pause() {
  try {
    audio_player.value?.pause();
  }
  catch (err) {
    console.log('err:', err);
  }
}

async function handleEdit(_row: number, _data: any) {

}

async function handleDelete(_index: number, data: any) {
  try {
    await ElMessageBox.confirm('确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    axios.delete(`api/songs/${data.song_id}/${data.file_path}`).then((response) => {
      console.log(response.data);
      ElMessage.success('删除成功');
      get_songs();
    }).catch((error) => {
      console.log(error);
      ElMessage.error('删除失败');
    })
  }
  catch (err) {
    console.log(err);
  }


}

async function handleDownload(_index: number, data: any) {
  try {
    let res = await axios.get(`/api/songs/get_download_url2/${data.id}`)
    let file_url = res.data.data.url
    const link = document.createElement('a');
    link.href = file_url;
    console.log('link.href:', link.href);
    link.download = new URL(file_url).pathname.split('/').pop()!;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
  catch (err) {
    console.log('err:', err);
  }
}

function handleSizeChange(val: number) {
  console.log(`每页 ${val} 条`);
  page_size.value = val;
}

function handleCurrentChange(val: number) {
  console.log(`当前页: ${val}`);
  page_num.value = val;
  get_songs();
}

onMounted(() => {
  console.log(route.params);

  get_songs();
});

function get_songs() {
  axios.get('api/songs/get_songs', {
    params: {
      page: page_num.value,
      per_page: page_size.value
    },
  }).then((response) => {
    songs.value = response.data.data.songs;
    total_count.value = response.data.data.pagination.total;
    console.log(response.data);
  }).catch((error) => {
    console.log(error);
    ElMessage.error('获取歌曲列表失败');
  })
}

function upload() {
  console.log('upload');
  uploadDialogVisible.value = true;
}


</script>

<style lang="scss" scoped>
$container-background-color: #dae5f1;

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 800px;
}

.root {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #d1dbe6;
  display: flex;
}

.el-main {
  //   display: flex;
  padding: 6px;
  // background-color: blueviolet;
}

.main-container {
  width: 100%;
  height: 100%;
  // background-color: aquamarine;
  // margin: {top: 10px;bottom: 10px; left: 0px; right: 6px;}
  margin: 0;
  display: flex;
  flex-direction: column;
  // background-color: aqua;
  // background-color: $container-background-color;

}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.header {
  display: flex;
  justify-content: flex-end;
  /* 将内容靠右对齐 */
  align-items: center;
  /* 垂直居中 */
  height: 60px;
  /* 设置 header 的高度 */

}

.button-group {
  display: flex;
  gap: 10px;
  /* 设置按钮之间的间距 */
}

.aside {
  // width: 100%; /* 父容器宽度填满页面 */
  // height: 200px; /* 父容器的高度 */
  border: 2px solid #d1ddc6;
}

.footer {
  border: 2px solid #d1ddc6;
}




.table {
  flex: 1;
  /* 表格占据剩余空间 */
  overflow-y: auto;
  /* 如果表格内容过多，显示滚动条 */
}

.pagination-block {
  display: flex;
  justify-content: center;
}
</style>